﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!(User.IsInRole("Administrator") || User.IsInRole("Employee")))
        {
            Response.Redirect("CustomerView.aspx");
        }
    }
    protected void Click_Logout(object sender, EventArgs e)
    {
        System.Web.Security.FormsAuthentication.SignOut();
        Response.Redirect("Login.aspx");
    }
   


    protected void AddCustomer(object sender, EventArgs e)
    {
        //using LINQ to SQL, add the new customer to the DB
        using (TimeTrackerDataContext context = new TimeTrackerDataContext())
        {
            Customer tempCustomer = new Customer
            {
                 
                customerName = TextBoxCustomerName.Text
            };
            context.Customers.InsertOnSubmit(tempCustomer);
            context.SubmitChanges();
        }
        GridViewCustomers.DataBind();
        this.Panel1.Visible = false;
        this.GridViewCustomers.Visible = true;
    }

    protected void AddProject(object sender, EventArgs e)
    {
        if (this.Page.IsValid)
        {
            //Using LINQ to SQL, update/Add the project
            using (TimeTrackerDataContext context = new TimeTrackerDataContext())
            {
                int tempID;
                DateTime StartDate;
                DateTime EndDate;
                decimal elapsedTime;
                System.Int32.TryParse(DropDownList1.SelectedValue, out tempID);
                System.Decimal.TryParse(TextBoxElapsedTime.Text, out elapsedTime);
                System.DateTime.TryParse(TextBoxEndDate.Text, out EndDate);
                System.DateTime.TryParse(TextBoxStartDate.Text, out StartDate);

                //If we don't have a projectID, then it's a new project
                if (String.IsNullOrEmpty(ProjectID.Value))
                {
                    Project tempProject = new Project
                    {
                        name = TextBoxProject.Text,
                        customerID = tempID,
                        startDate = StartDate,
                        endDate = EndDate,
                        timeTotal = elapsedTime
                    };
                    context.Projects.InsertOnSubmit(tempProject);
                    context.SubmitChanges();
                }
                else
                {
                    //Update the Project and Submit the changes
                    int selectedProjectId;
                    System.Int32.TryParse(ProjectID.Value.Trim(), out selectedProjectId);
                    Project tempProject = context.Projects.Single(p => p.id == selectedProjectId);

                    tempProject.name = TextBoxProject.Text;
                    tempProject.customerID = tempID;
                    tempProject.startDate = StartDate;
                    tempProject.endDate = EndDate;
                    tempProject.timeTotal = elapsedTime;

                    context.SubmitChanges();

                }

            }
            GridViewProjects.DataBind();
            this.PanelProject.Visible = false;
            this.GridViewProjects.Visible = true;
        }
        else
        {
            this.TextBoxElapsedTime.Text = "";
            this.TextBoxEndDate.Text = "";
            this.TextBoxProject.Text = "";
            this.TextBoxStartDate.Text = "";

            this.PanelAddTimeEntries.Visible = false;


            this.Panel1.Visible = false;
            this.GridViewCustomers.Visible = false;
            this.GridViewProjects.Visible = false;
            this.PanelProject.Visible = true;
            this.PanelReport.Visible = false;
        }

    }


    protected void SelectProject(object sender, EventArgs e)
    {
        int selectedProjectId;
        decimal totalTime = 0;

        this.TreeView1.Nodes[1].Selected = false;
        // Parse the Project ID from the DataGrid's selected row
        System.Int32.TryParse(GridViewProjects.SelectedRow.Cells[1].Text.Trim(), out selectedProjectId);
        TimeTrackerDataContext context = new TimeTrackerDataContext();

        Project tempProject = context.Projects.Single(p => p.id == selectedProjectId);

        var timePieces = (from te in context.timeEntries
                          where te.projectID == selectedProjectId
                          orderby te.timestamp
                          select te);
        this.ListBoxTimes.Items.Clear();
        this.TextBoxEntry.Text = "";
        foreach (timeEntry entry in timePieces)
        {
            //Get the Edits for Project
            string tempLine = entry.timestamp + " - Added " + entry.timeInterval + "Hrs.";
            if(!String.IsNullOrEmpty(entry.Employee.emailAddress))
                tempLine += " by " +entry.Employee.emailAddress;
            this.ListBoxTimes.Items.Add(tempLine);
            totalTime += entry.timeInterval;
        }

        this.TextBoxCustomer.Visible = true;
        this.DropDownList1.Visible = false;
        this.LabeltimeSheet.Visible = true;
        this.ListBoxTimes.Visible = true;

        

        //Set the values, and make the project panel visible
        PanelProject.Visible = true;
        TextBoxElapsedTime.Text = totalTime.ToString() + "Hrs.";
        TextBoxElapsedTime.ReadOnly = true;
        TextBoxEndDate.Text = ((DateTime)tempProject.endDate).ToString(@"MM/dd/yyyy");
        TextBoxEndDate.ReadOnly = true;
        this.CalendarExtenderEndDate.Enabled = false;
        TextBoxStartDate.Text = ((DateTime)tempProject.startDate).ToString(@"MM/dd/yyyy");
        this.CalendarExtenderStartDate.Enabled = false;
        TextBoxStartDate.ReadOnly = true;
        TextBoxProject.Text = tempProject.name;
        TextBoxProject.ReadOnly = true;
        this.TextBoxCustomer.Text = tempProject.Customer.customerName.ToString();
        ProjectID.Value = tempProject.id.ToString();
        Label2.Text = "Update Project";
        this.GridViewProjects.Visible = false;
    }
    protected void AddEntry(object sender, EventArgs e)
    {
        TimeTrackerDataContext context = new TimeTrackerDataContext();
        int selectedProjectId;
        // Parse the Project ID from the DataGrid's selected row
        System.Int32.TryParse(GridViewProjects.SelectedRow.Cells[1].Text.Trim(), out selectedProjectId);

        MembershipUser user = Membership.GetUser();

        var emp = (from E in context.Employees
                   where E.userID == (Guid)user.ProviderUserKey
                   select E).Single();

        timeEntry entry = new timeEntry();
        entry.timeInterval = Decimal.Parse(this.TextBoxEntry.Text);
        entry.EmployeeID = emp.ID;
        entry.projectID = selectedProjectId;
        entry.timestamp = DateTime.Now;

        context.timeEntries.InsertOnSubmit(entry);
        context.SubmitChanges();

        this.ListBoxTimes.Items.Add(entry.timestamp + " - Added " + entry.timeInterval + "Hrs.");
        this.TextBoxElapsedTime.Text = (Decimal.Parse(this.TextBoxElapsedTime.Text.Replace("Hrs.","")) + entry.timeInterval).ToString()+"Hrs.";

        this.TextBoxEntry.Text = "";
        
    }

    protected string GetTotalTime(int id)
    {
        TimeTrackerDataContext context = new TimeTrackerDataContext();
        decimal total = 0;

        var entries = (from te in context.timeEntries
                       where te.projectID == id
                       select te);
        if (entries.Count() > 0 )
            total = entries.Sum(t => t.timeInterval);

        return total.ToString();
    }

    protected void Tree_Clicked(object sender, EventArgs e)
    {

        switch (TreeView1.SelectedNode.Text)
        {
            case "Customer List":
                this.GridViewCustomers.Visible = true;
                this.Panel1.Visible = false;
                this.GridViewProjects.Visible = false;
                this.PanelProject.Visible = false;
                this.PanelReport.Visible = false;
                break;

            case "Create New Customer":
                //Clear the customer name, since we're still working with the same page state
                this.TextBoxCustomerName.Text = "";
                this.Panel1.Visible = true;
                this.GridViewCustomers.Visible = false;
                this.GridViewProjects.Visible = false;
                this.PanelProject.Visible = false;
                this.PanelReport.Visible = false;
                break;

            case "Task List":
                this.Panel1.Visible = false;
                this.GridViewCustomers.Visible = false;
                this.GridViewProjects.Visible = true;
                this.PanelProject.Visible = false;
                this.PanelReport.Visible = false;
                this.PanelAddTimeEntries.Visible = true;
                this.DropDownList1.Visible = true;
                this.GridViewProjects.DataBind();
                break;

            case "Create a New Task":
                //Clear the fields, since we're still working the same page state
                this.TextBoxElapsedTime.Text = "";
                this.TextBoxEndDate.Text = "";
                this.TextBoxProject.Text = "";
                this.TextBoxStartDate.Text = "";

                this.PanelAddTimeEntries.Visible = false;
                this.TextBoxCustomer.Visible = false;
                this.ListBoxTimes.Visible = false;
                this.LabeltimeSheet.Visible = false;

                TextBoxElapsedTime.ReadOnly = false;
                TextBoxEndDate.ReadOnly = false;
                this.CalendarExtenderEndDate.Enabled = true;
                this.CalendarExtenderStartDate.Enabled = true;
                TextBoxEndDate.ReadOnly = false;
                TextBoxProject.ReadOnly = false;


                this.Panel1.Visible = false;
                this.GridViewCustomers.Visible = false;
                this.GridViewProjects.Visible = false;
                this.PanelProject.Visible = true;
                this.PanelReport.Visible = false;
                this.DropDownList1.DataBind();
                break;

            case "Reporting":
                this.DataList1.DataBind();
                this.Panel1.Visible = false;
                this.GridViewCustomers.Visible = false;
                this.GridViewProjects.Visible = false;
                this.PanelProject.Visible = false;
                this.PanelReport.Visible = true;
                break;


            default:
                //Default view is the customer list
                this.GridViewCustomers.Visible = true;
                break;

        }
    }
    protected void DeleteCustomer(object sender, GridViewDeleteEventArgs e)
    {
        TimeTrackerDataContext context = new TimeTrackerDataContext();

    }
}
